package com.cxx.framework.app.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

import com.cxx.purchasecharge.component.bean.PCApplicationContext;

/**
 * Default logout success handler that audits the user logout event. Subclasses
 * should override onLogoutSuccess(HttpServletRequest, HttpServletResponse,
 * Authentication) and call super.onLogoutSuccess(HttpServletRequest,
 * HttpServletResponse, Authentication).
 * 
 */
public class BaseLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler
{
    private static final Logger logger = Logger.getLogger (BaseLogoutSuccessHandler.class);
    private PCApplicationContext pcContext;

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.web.authentication.logout.
     * SimpleUrlLogoutSuccessHandler
     * #onLogoutSuccess(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse,
     * org.springframework.security.core.Authentication)
     */
    @Override
    public void onLogoutSuccess (HttpServletRequest request, HttpServletResponse response, Authentication authentication)
                                                                                                                         throws IOException,
                                                                                                                         ServletException
    {
        if (null != authentication)
        {
            User user = (User) authentication.getPrincipal ();
            String userId = user.getUsername ();
            pcContext.removeLoginUser (userId);
            logger.debug ("User: " + userId + " Logout completed");
        }
        super.onLogoutSuccess (request, response, authentication);
    }

    public PCApplicationContext getPcContext ()
    {
        return pcContext;
    }

    public void setPcContext (PCApplicationContext pcContext)
    {
        this.pcContext = pcContext;
    }

}
